package com.taobao.tql.parser;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.taobao.tql.scan.GetApiImpl;

/**
 * 解析TOP页面上的js数据
 * 
 * @类名称：JsEngine
 * @类描述：
 * @创建人：卫缺
 * @修改人：卫缺
 * @修改时间：2011-6-30 下午01:23:34
 * @修改备注：
 * @version 1.0.0
 * 
 */
public class JsEngine {

	private static ScriptEngineManager factory = new ScriptEngineManager();// step
																			// 1
	private static ScriptEngine engine = factory.getEngineByName("JavaScript");// Step
																				// 2
	
	

	/**
	 * 
	 * getFileds(这里用一句话描述这个方法的作用) 获取top平台页面的fields字段 获取fields字段
	 * 
	 * @param strKey
	 * @return
	 * @throws Exception
	 *             String
	 * @since 1.0.0
	 */
	public static String getFileds(String strKey) {
		String res = null;
		try {

			StringBuffer scriptBuf = new StringBuffer(
					"var defaultFields = eval('(' + '[{\"key\":\"taobao.item.sku.get\",\"value\":\"sku_id,num_iid,properties,quantity,price,outer_id,created,modified,status\"},{\"key\":\"taobao.items.search\",\"value\":\"num_iid,title,nick,pic_url,cid,price,type,delist_time,post_fee,score,volume\"},{\"key\":\"taobao.items.onsale.get\",\"value\":\"approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id\"},{\"key\":\"taobao.products.search\",\"value\":\"product_id,cid,props,name,pic_url\"},{\"key\":\"taobao.itemprops.get\",\"value\":\"pid,name,must,multi,prop_values\"},{\"key\":\"taobao.users.get\",\"value\":\"user_id,nick,sex,buyer_credit,seller_credit,location,created,last_visit\"},{\"key\":\"taobao.taobaoke.items.convert\",\"value\":\"click_url,num_iid,commission,commission_rate,commission_num,commission_volume\"},{\"key\":\"taobao.logistics.orders.get\",\"value\":\"tid,seller_nick,buyer_nick,delivery_start,delivery_end,out_sid,item_title,receiver_name,created,modified,status,type,freight_payer,seller_confirm,company_name\"},{\"key\":\"taobao.taobaoke.report.get\",\"value\":\"trade_id,pay_time,pay_price,num_iid,outer_code,commission_rate,commission,seller_nick,pay_time,app_key\"},{\"key\":\"taobao.items.inventory.get\",\"value\":\"approve_status,num_iid,title,nick,type,cid,pic_url,num,props,valid_thru,list_time,price,has_discount,has_invoice,has_warranty,has_showcase,modified,delist_time,postage_id,seller_cids,outer_id\"},{\"key\":\"taobao.shopcats.list.get\",\"value\":\"cid,parent_cid,name,is_parent\"},{\"key\":\"taobao.trades.bought.get\",\"value\":\"seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type\"},{\"key\":\"taobao.item.get\",\"value\":\"detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual\"},{\"key\":\"taobao.trades.sold.get\",\"value\":\"seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type\"},{\"key\":\"taobao.traderates.get\",\"value\":\"tid,oid,role,rated_nick,nick,result,created,item_title,item_price,content,reply\"},{\"key\":\"taobao.itemcats.get\",\"value\":\"cid,parent_cid,name,is_parent\"},{\"key\":\"taobao.items.custom.get\",\"value\":\"num_iid,sku,item_img,prop_img\"},{\"key\":\"taobao.logistics.orders.detail.get\",\"value\":\"tid,buyer_nick,receiver_name,receiver_mobile,receiver_phone,receiver_location\"},{\"key\":\"taobao.user.get\",\"value\":\"user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind\"},{\"key\":\"taobao.skus.custom.get\",\"value\":\"sku_id,properties\"},{\"key\":\"taobao.itempropvalues.get\",\"value\":\"cid,pid,prop_name,vid,name,name_alias,status,sort_order\"},{\"key\":\"taobao.postage.get\",\"value\":\"postage_id,name,memo,post_price,post_increase,express_price,express_increase,ems_price,ems_increase,postage_mode.id,postage_mode.type,postage_mode.dest,postage_mode.price,postage_mode.increase\"},{\"key\":\"taobao.itemcats.authorize.get\",\"value\":\"brand.vid,brand.name,item_cat.cid,item_cat.name,item_cat.status,item_cat.sort_order,item_cat.parent_cid,item_cat.is_parent\"},{\"key\":\"taobao.products.get\",\"value\":\"product_id,outer_id,created,cid,cat_name,props,props_str,name,binds,binds_str,sale_props,desc,pic_url,modified\"},{\"key\":\"taobao.taobaoke.shops.convert\",\"value\":\"shop_title,click_url,commission_rate\"},{\"key\":\"taobao.areas.get\",\"value\":\"id,type,name,parent_id,zip\"},{\"key\":\"taobao.taobaoke.items.detail.get\",\"value\":\"click_url,shop_click_url,seller_credit_score,num_iid,title,nick\"},{\"key\":\"taobao.product.get\",\"value\":\"product_id,cid,cat_name,props,props_str,name,binds,binds_str,sale_props,sale_props_str,price,desc,pic_url,created,modified,product_img.id,product_img.url,product_img.position,product_prop_img.id,product_prop_img.props,product_prop_img.url,product_prop_img.position\"},{\"key\":\"taobao.item.skus.get\",\"value\":\"sku_id,num_iid,properties,quantity,price,outer_id,created,modified\"},{\"key\":\"taobao.trades.sold.increment.get\",\"value\":\"seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type\"},{\"key\":\"taobao.shop.get\",\"value\":\"sid,cid,title,nick,desc,bulletin,pic_path,created,modified\"},{\"key\":\"taobao.items.get\",\"value\":\"num_iid,title,nick,pic_url,cid,price,type,delist_time,post_fee,score,volume\"},{\"key\":\"taobao.trade.fullinfo.get\",\"value\":\"seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type\"},{\"key\":\"taobao.taobaoke.items.get\",\"value\":\"num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume\"},{\"key\":\"taobao.postages.get\",\"value\":\"postage_id,name,post_price,post_increase,express_price,express_increase,ems_price,ems_increase,postage_mode.id,postage_mode.type,postage_mode.dests,postage_mode.price\"}]' + ')');");
			scriptBuf
					.append("function getDefaultFields(key) {for(i=0;i<defaultFields.length;i++) {if(defaultFields[i].key == key) {return defaultFields[i].value;break;}} return \"\";}");
			engine.eval(scriptBuf.toString());
			Invocable inv = (Invocable) engine;
			res = (String) inv.invokeFunction("getDefaultFields", strKey);
			System.out.println("res:" + res);
			return res;
		} catch (Exception ex) {
			ex.fillInStackTrace();
			return "";
		}

	}

	public static String getMustInput(String strKey) {
		String res = null;
		try {
			StringBuffer scriptBuf = new StringBuffer(initPrePar().toString());
			scriptBuf.append("function getApiListByCategoryId(o) {");
			scriptBuf.append("var cateId = o;");
			scriptBuf.append("categoryId = cateId;");

			scriptBuf.append("var url = 'http://my.open.taobao.com/apitools/getApiList.htm?cid='+cateId;");
			scriptBuf.append("getXmlHttp();");
			scriptBuf.append("xmlHttp.open('GET', url, false);");
			scriptBuf.append("xmlHttp.send(null);");
			scriptBuf.append("if(xmlHttp.readyState == 4) {");
			scriptBuf.append("if(xmlHttp.status == 200) {");
			scriptBuf.append("response = xmlHttp.responseText;");
			scriptBuf.append("apiArr = eval(\"(\" + response + \")\");");
			scriptBuf.append("}");
			scriptBuf.append("}");
			scriptBuf.append("");

			scriptBuf.append("}");
			engine.eval(scriptBuf.toString());
			Invocable inv = (Invocable) engine;
			res = (String) inv.invokeFunction("getApiListByCategoryId", GetApiImpl.getInstantce().getApiKey(strKey));
			System.out.println("res:" + res);
			return res;
		} catch (Exception ex) {
			ex.fillInStackTrace();
			return "";
		}

	}

	private static String initPrePar() {
		StringBuilder strBuild = new StringBuilder();
		strBuild.append("var xmlHttp;");
		strBuild.append("var apiArr = new Array();");
		strBuild.append("var apiParamArr = new Array();");
		strBuild.append("var categoryId=0;");
		strBuild.append("var api_name=\"\";");

		strBuild.append("if(window.ActiveXObject) {");
		strBuild.append("xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");");
		strBuild.append("} else {");
		strBuild.append("xmlHttp = new XMLHttpRequest();");
		strBuild.append("}");
		strBuild.append("function getXmlHttp() {");
		strBuild.append("if(window.ActiveXObject) {");
		strBuild.append("xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\");");
		strBuild.append("} else {");
		strBuild.append("xmlHttp = new XMLHttpRequest();");
		strBuild.append("}");
		strBuild.append("return xmlHttp;");
		strBuild.append("}");
		strBuild.append("return strBuild.toString();");
		strBuild.append("}");
		return strBuild.toString();
	}
	

	public static void main(String[] arges) {
		String key = "product";
		try {
			System.out.println(getMustInput(key));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
